import type { ComponentExposed } from 'vue-component-type-helpers'
import type { DataFormField } from '../DataField'
import type { DataFormProp } from '@/components/DataForm/types'
import { defineComponent, h, reactive, ref, useTemplateRef } from 'vue'
import DataForm from './DataForm.vue'

export function useEditForm<T extends Record<string, any>>({ editFields = [] }: {
  editFields: DataFormField[]
}) {
  const editFormData = ref<Partial<T>>({})
  const editFormSubmit = ref<((data: T) => Promise<any>)>()
  let editFormRef = useTemplateRef<ComponentExposed<typeof DataForm>>('editFormRef')

  const editFormFields = reactive<DataFormField[]>(editFields)
  const submitLoading = ref(false)

  const EditForm = defineComponent(
    (props: DataFormProp<T>, { attrs, slots }) => {
      editFormRef = useTemplateRef<ComponentExposed<typeof DataForm>>('editFormRef')
      return () => h(DataForm<T>, {
        ref: 'editFormRef',
        cols: 1,
        fields: editFormFields,
        modelValue: editFormData.value,
        submit: editFormSubmit.value,
        ...props,
        ...attrs,
      }, slots)
    },
  )

  async function submitEditForm(title: string, submit: (data: T) => Promise<any>) {
    if (submitLoading.value === true)
      return
    editFormSubmit.value = submit
    submitLoading.value = true
    try {
      const result = await editFormRef.value?.submitForm()
      ElMessage.success(`${title}成功`)
      return result
    }
    finally {
      submitLoading.value = false
    }
  }

  return {
    editFormData,
    editFormFields,
    submitEditForm,
    submitLoading,
    EditForm,
  }
}
